<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
  <head>
    <title>新增组合</title>
    <script type="text/javascript">
      Ext.onReady(function(){
        //是否临时保存
        var temporary = Ext.create('Ext.form.field.Hidden', {
          name: 'temporary',
          value: 0
        });
        //所有仓库        
        var fromWarehouse = Ext.create('Ext.form.ComboBox', {
          store: warehouseStore,
          fieldLabel: '选择仓库',
          allowBlank: false,
          blankText: "仓库必须选择",
          emptyText: '请选择...',
          valueField: 'id',
          displayField: 'name',
          name: 'warehouse_id',          
          loadingText: '搜索中...',
          anchor: '90%',
          //pageSize: 10,
          minChars: 0,
          triggerAction:'all'
        });        

        var description = Ext.create('Ext.form.field.Text', {
          fieldLabel: '备注',
          name: 'description',
          anchor: '95%'
        });

        //产品
        var productCBB = Ext.create('Ext.form.ComboBox', {
          store: productSuitStore,
          emptyText: '请选择...',
          displayField: 'name',
          loadingText: '搜索中...',
          anchor: '100%',
          minChars: 0,
          listConfig: {
            loadingText: 'Searching...',
            getInnerTpl: function() {
              return '<div style="float:left; width:200px" data-qtip="{name}">{name:ellipsis(18)}</div><div style="float:left; width:110px">{number}</div>{is_suit}';
            }
          },
          pageSize: 10
        });

        productCBB.on('select', function(combo, record, index) {
          var records = assemblyOrderProductsGrid.getSelectionModel().getSelection();
          var assemblyProductRecord = records[0];
          if (!assemblyProductRecord) {
            return false;
          }
          //重复选择的产品予以去除。
          if (isDuplicateByProduct(assemblyOrderProductsDS,record[0].get('id'),assemblyProductRecord.product_id)){
            //删除当前记录
            assemblyOrderProductsDS.remove(assemblyProductRecord);
          }else{
            assemblyProductRecord.set('number',record[0].get('number'));
            assemblyProductRecord.set('spec',record[0].get('spec'));
            assemblyProductRecord.set('unit',record[0].get('unit'));
            assemblyProductRecord.set('quantity',record[0].get('quantity'));
            assemblyProductRecord.set('product_id',record[0].get('id'));
            //判断套装
            assemblyProductRecord.set('is_suit',record[0].get('is_suit'));
            assemblyProductRecord.set('quantity',1);
            subProductDS.getProxy().extraParams.id = record[0].get('id');
            subProductDS.load();
            subProductGrid.setTitle("产品："+record[0].get('number')+"，的组成明细");
          }
        });

        var assemblyOrderProductsDS = Ext.create('Ext.data.Store', {
          autoDestroy : true,
          model : 'AssemblyOrderProductModel',
          proxy : {
            type : 'ajax',
            //url : '/sale_order/getSaleOrderDetailsBalanceById',
            reader : {
              type : 'json',
              root : 'root',
              totalProperty : 'totalProperty'// 数据集记录总数
            }
          }
        });

        var cellEditing = Ext.create('Ext.grid.plugin.CellEditing', {
          clicksToEdit: 1
        });
        
        //生成要订单的产品的Grid
        var assemblyOrderProductsGrid = Ext.create('Ext.grid.Panel', {
          store: assemblyOrderProductsDS,
          columns : [Ext.create('Ext.grid.RowNumberer'),{
              header: '产品名称',
              dataIndex: 'product_name',
              field: productCBB,
              width: 370
            },{
              header: '产品ID',
              dataIndex: 'product_id',
              width: 50,
              hidden: false
            },{
              header: '产品编号',
              dataIndex: 'number',
              width: 95
            },{
              header: '规格',
              dataIndex: 'spec',
              width: 50
            },{
              header: '单位',
              dataIndex: 'unit',
              width: 40
            },{
              header: '数量',
              dataIndex: 'quantity',
              field: Ext.create('Ext.form.field.Number', {
                allowBlank: false,
                allowDecimals: false,
                minValue: 1
              }),
              align: 'right',
              width: 50
            },{
              header: '套装或单品',
              dataIndex: 'is_suit',
              width: 70
            },{
              header: '备注',
              dataIndex: 'description',
              width: 160,
              field:Ext.create('Ext.form.field.Text', {
                name: 'description',
                anchor: '100%'
              })
            }],
          selModel :Ext.create('Ext.selection.CheckboxModel'),
          /*selModel: {
            selType: 'cellmodel'
          },*/
          plugins: [cellEditing],
          width: 960,
          height: 265,
          tbar: [{
              text: '添加产品',
              iconCls: 'addItem',
              handler : function(){
                var record = Ext.ModelManager.create({
                  product_name: '请选择产品'
                }, assemblyOrderProductsGrid.getStore().model);
                assemblyOrderProductsDS.insert(0, record);
              }
            },{
              text: '删除',
              iconCls: 'remove',
              handler : function(){
                var records = assemblyOrderProductsGrid.getSelectionModel().getSelection();
                cellEditing.cancelEdit();
                assemblyOrderProductsDS.remove(records);
              }
            }]
        });

        assemblyOrderProductsGrid.on('itemdblclick', function(gridPanel, record,item,index,e,options){
          productId = record.get('product_id');
          subProductDS.removeAll();
          subProductDS.getProxy().extraParams.id = productId;
          subProductDS.load();
          subProductGrid.setTitle("产品："+record.get('number')+"，的组成明细");
        });

        //将要组合的货品Grid Store
        var subProductDS = Ext.create('Ext.data.Store', {
          autoDestroy : true,
          model : 'SubProductModel',
          proxy : {
            type : 'ajax',
            url: '/product/getAllComponentsById',
            reader : {
              type : 'json',
              root : 'root',
              totalProperty : 'totalProperty'// 数据集记录总数
            }
          }
        });
        
        //生成要订单的产品的Grid
        var subProductGrid = Ext.create('Ext.grid.Panel', {
          store: subProductDS,
          columns : [Ext.create('Ext.grid.RowNumberer'),{
              header: 'DB',
              dataIndex: 'id',
              width: 60
            },{
              header: '产品名称',
              dataIndex: 'name',
              width: 270
            },{
              header: '产品编号',
              dataIndex: 'number',
              width: 120
            },{
              header: '规格',
              dataIndex: 'spec',
              width: 80
            },{
              header: '单位',
              dataIndex: 'unit',
              width: 80
            },{
              header: '数量',
              align: 'right',
              dataIndex: 'quantity',
              width: 80
            },{
              header: '套装或单品',
              dataIndex: 'is_suit',
              width: 70
            }],
          selModel :Ext.create('Ext.selection.CheckboxModel'),
          width: 960,
          height: 300,
          //frame: true,
          title: '产品组成列表'
          //frame: true,
          //plugins: checkColumn,
        });

        //暂时保存按钮
        var submitButton = Ext.create('Ext.Button', {
          text: '提交',
          tooltip: '提交组合单。',
          iconCls: 'icon-save',
          handler: function(){
            
            assemblySubmit();
          }
        });

        //临时保存按钮
        var tempSaveButton = Ext.create('Ext.Button', {
          text: '暂存',
          tooltip: '暂时保存销售订单。',
          iconCls: 'temp-save',
          handler: function(){
            
            assemblySubmit("temp");
          }
        });

        function assemblySubmit(submitType){
          //首先把临时变量设置为1
          if(submitType === "temp"){
            temporary.setValue(1);
          }
          

          if (assemblyFormPanel.form.isValid()){
            tempSaveButton.setDisabled(true);
            submitButton.setDisabled(true);
            var productsJsonStr = gridStoreToJson(assemblyOrderProductsDS,rejectKeyArray);
            var allJsonStr = assemblyFormPanel.getForm().getValues();
            allJsonStr = Ext.JSON.encode(allJsonStr);
            allJsonStr = Ext.util.Format.substr(allJsonStr,0,allJsonStr.length-1);
            allJsonStr = allJsonStr + ",\"products\":" + productsJsonStr + "}";
            Ext.Ajax.request({
              url: '/assembly_order/create',
              success : function (result, request) {
                if (Ext.JSON.decode(result.responseText).info.indexOf("成功") > -1) {
                  var msgInfo = "";
                  if(submitType === "temp"){
                    msgInfo = "暂存组合订单，操作成功！";
                  }else{
                    msgInfo = "新增组合订单，操作成功！";
                  }
                  Ext.MessageBox.show({
                    title: '消息',
                    msg: msgInfo,
                    buttons: Ext.MessageBox.OK,
                    icon: Ext.MessageBox.INFO
                  });
                }
                else {
                  Ext.MessageBox.show({
                    title: '消息',
                    msg: Ext.JSON.decode(result.responseText).info,
                    buttons: Ext.MessageBox.OK,
                    icon: Ext.MessageBox.WARNING
                  });
                }
                newAssemblyWin.destroy();
              },
              failure : function (result, request){
                Ext.MessageBox.show({
                  title: '消息',
                  msg: "通讯失败，请从新操作",
                  buttons: Ext.MessageBox.OK,
                  icon: Ext.MessageBox.WARNING
                });
                newAssemblyWin.destroy();
              },
              method : 'POST',
              params : {
                data : Ext.JSON.encode(allJsonStr),
                authenticity_token: authToken.getValue()
              }
            });
          }
        }

        //暂时保存按钮
        var closeButton = Ext.create('Ext.Button', {
          text: '关闭',
          tooltip: '关闭当前窗口，并且当前编辑的信息不能保存。',
          iconCls: 'exit',
          handler: function(){
            newAssemblyWin.destroy();
          }
        });
        
        var assemblyFormPanel = Ext.create('Ext.form.Panel', {
          fieldDefaults: {
            labelWidth: 55,
            labelAlign: 'right'
          },
          width: '950',
          frame : true,
          url: '/assembly_order/create',
          method: 'GET',
          //defaultType: 'textfield',
          items: [{
              xtype: 'fieldset',
              title: '组合产品必选项',
              defaults: {width: 940},
              border: true,
              items: [{
                  layout: 'column',
                  xtype: 'container',
                  items: [{
                      columnWidth: .2,
                      layout: 'anchor',
                      xtype: 'container',
                      items: [fromWarehouse]
                    }, {
                      columnWidth: .8,
                      layout: 'anchor',
                      xtype: 'container',
                      items: [description]
                    }]
                }]
            },assemblyOrderProductsGrid,subProductGrid,temporary],
          buttons: [submitButton,tempSaveButton,closeButton]
        });
        assemblyFormPanel.render('assembly_form');
      })
    </script>
  </head>
  <body>
    <div id="assembly_form"></div>
  </body>
</html>
